package com.link.serve.tcp.handler;

import com.alibaba.fastjson2.JSON;
import com.link.serve.constants.BizId;
import com.link.serve.constants.KafkaConstant;
import com.link.serve.downlink.messaging.ChatMessage;
import com.link.serve.kafka.producer.ImMessageProducer;
import com.link.serve.tcp.message.Message;
import com.link.serve.tcp.message.proto.PackHeader;
import com.link.serve.utils.MessageUtils;
import com.link.serve.utils.SpringContextHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 上行推送服务
 */
@Slf4j
@Component
public class UplinkMessageHandler extends SimpleChannelInboundHandler<Message> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        // 获取消息头
        PackHeader.Header header = msg.getHeader();
        int bizId = header.getBizId(); // 获取业务 ID
        // 验证业务 ID 是否有效
        if (!BizId.isValid(bizId)) {
            log.warn("收到未知业务ID: {}", bizId);
            Message response = MessageUtils.buildResponseMessage(header.getAppId(), header.getUid(), "收到未知业务ID", 99);
            ctx.channel().writeAndFlush(response);
            ctx.close(); // 关闭连接
            return;
        }

        // 处理上行推送
        boolean handled = handleUplinkPush(ctx, msg, bizId);

        // 如果未处理，传递给下一个 Handler
        if (!handled) ctx.fireChannelRead(msg);
    }

    private boolean handleUplinkPush(ChannelHandlerContext ctx, Message msg, int bizId) throws ClassNotFoundException {
        if (!BizId.isValid(bizId)) return false;

        switch (BizId.fromId(bizId)) {
            case IM:
                handleIMMessage(msg);
                return true;
            case LINK:
            default:
                return false;
        }
    }
    //IM服务的业务逻辑
    public void handleIMMessage(Message message) throws ClassNotFoundException {
        //spring获取
        ImMessageProducer imMessageProducer = SpringContextHolder.getBean(ImMessageProducer.class);
        //消息推送先解析消息头 根据会话id来进行分片
        ChatMessage chatMessage = JSON.parseObject(message.getBody().getData(), ChatMessage.class);
        log.info("收到消息: {}", message);
        imMessageProducer.sendImMessage(chatMessage.getSessionId(), message);
    }
}
